#!/usr/bin/env python3
"""
测试InternVL API调用格式
"""
import asyncio
import httpx
import base64
from pathlib import Path
import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

async def test_api_formats():
    """测试不同的API调用格式"""
    
    api_key = os.getenv("INTERNVL_API_KEY")
    base_url = os.getenv("INTERNVL_BASE_URL")
    model_name = os.getenv("INTERNVL_MODEL_NAME")
    
    if not all([api_key, base_url, model_name]):
        print("❌ 请确保环境变量已配置")
        return
    
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    
    # 测试1: 简单文本请求
    print("🧪 测试1: 简单文本请求")
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.post(
                f"{base_url}/chat/completions",
                headers=headers,
                json={
                    "model": model_name,
                    "messages": [
                        {
                            "role": "user",
                            "content": "你好，请介绍一下你自己。"
                        }
                    ],
                    "stream": False,
                    "max_tokens": 100,
                    "temperature": 0.7
                }
            )
            
            if response.status_code == 200:
                result = response.json()
                print("✅ 文本请求成功")
                print(f"响应: {result.get('choices', [{}])[0].get('message', {}).get('content', 'No content')}")
            else:
                print(f"❌ 文本请求失败: {response.status_code} - {response.text}")
                
    except Exception as e:
        print(f"❌ 文本请求异常: {e}")
    
    print("\n" + "="*50 + "\n")
    
    # 测试2: 检查模型列表
    print("🧪 测试2: 检查可用模型")
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{base_url}/models",
                headers=headers
            )
            
            if response.status_code == 200:
                models = response.json()
                print("✅ 模型列表获取成功")
                print(f"可用模型: {models}")
            else:
                print(f"❌ 模型列表获取失败: {response.status_code} - {response.text}")
                
    except Exception as e:
        print(f"❌ 模型列表获取异常: {e}")
    
    print("\n" + "="*50 + "\n")
    
    # 测试3: 图像请求格式（用于验证多模态格式）
    print("🧪 测试3: 多模态请求格式测试")
    
    # 创建一个简单的测试图像（1x1像素的PNG）
    test_image_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
    
    test_formats = [
        {
            "name": "格式1: image_url类型",
            "content": [
                {"type": "text", "text": "请描述这张图片"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/png;base64,{test_image_b64}"
                    }
                }
            ]
        },
        {
            "name": "格式2: 带<video>标记",
            "content": [
                {"type": "text", "text": "<video>\n请描述这个内容"},
                {
                    "type": "image_url", 
                    "image_url": {
                        "url": f"data:image/png;base64,{test_image_b64}"
                    }
                }
            ]
        }
    ]
    
    for test_format in test_formats:
        print(f"测试 {test_format['name']}")
        try:
            async with httpx.AsyncClient(timeout=30.0) as client:
                response = await client.post(
                    f"{base_url}/chat/completions",
                    headers=headers,
                    json={
                        "model": model_name,
                        "messages": [
                            {
                                "role": "user",
                                "content": test_format["content"]
                            }
                        ],
                        "stream": False,
                        "max_tokens": 100,
                        "temperature": 0.7
                    }
                )
                
                if response.status_code == 200:
                    result = response.json()
                    print(f"✅ {test_format['name']} 成功")
                    print(f"响应: {result.get('choices', [{}])[0].get('message', {}).get('content', 'No content')}")
                else:
                    print(f"❌ {test_format['name']} 失败: {response.status_code}")
                    print(f"错误详情: {response.text}")
                    
        except Exception as e:
            print(f"❌ {test_format['name']} 异常: {e}")
        
        print("-" * 30)

if __name__ == "__main__":
    asyncio.run(test_api_formats())